package com.chen.springboot.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.springboot.entity.Item;
import com.chen.springboot.entity.ItemDetail;
import com.chen.springboot.entity.User;
import com.chen.springboot.mapper.ItemDetailMapper;
import com.chen.springboot.mapper.ItemMapper;
import com.chen.springboot.mapper.UserMapper;
import com.chen.springboot.service.ItemService;
import org.apache.logging.log4j.util.Strings;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper,Item> implements ItemService {

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    ItemDetailMapper itemDetailMapper;

    @Override
    public List<Item> getAll(String search) {
        LambdaQueryWrapper<Item> wrapper = Wrappers.lambdaQuery();
        wrapper.orderByDesc(Item::getCreated);
        if (!Strings.isBlank(search))
            wrapper.like(Item::getSellPoint, search);
        return itemMapper.selectList(wrapper);
    }

    //新增商品
//    @Override
//    public void save(Item item) {
//        Date currDate = new Date();
//        item.setCreated(currDate);
//        if (item.getCid() == null) {
//            item.setCid(1L);
//        }
//        itemMapper.insert(item);
//        // 新增空白的商品详情
//        ItemDetail itemDetail = new ItemDetail();
//        itemDetail.setItemId(item.getId());
//        itemDetail.setItemDetail("<p></p>");
//        itemDetail.setCreateTime(currDate);
//        itemDetailMapper.insert(itemDetail);
//    }
    @Override
    public void saveItem(Item item) {
        Date currDate = new Date();
        item.setCreated(currDate);
        if (item.getCid() == null) {
            item.setCid(1L);
        }

        itemMapper.insert(item);

        ItemDetail itemDetail = new ItemDetail();
        itemDetail.setItemId(item.getId());
        itemDetail.setItemDetail("<p></p>");
        itemDetail.setCreateTime(currDate);
        itemDetailMapper.insert(itemDetail);
    }

    @Override
    public void update(Item item) {
        item.setUpdated(new Date());
        itemMapper.updateById(item);
    }

    //删除商品
    @Override
    public void delete(Long id) {
        itemMapper.deleteById(id);
    }

    //    //批量删除商品
    @Override
    public void deleteBatch(List<Long> ids) {
        itemMapper.deleteBatchIds(ids);
    }
    //分页查询get
    @Override
    public Page<Item> findPage(Integer pageNum, Integer pageSize, String search) {
        //新建分页对象
        Page<Item> page = new Page<>(pageNum, pageSize);
        //新建模糊查询对象,这里有个注意事项，你模糊项查询的对应项不能为null，为null就查不出来
        //LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>lambdaQuery().like(User::getUsername, search);
        LambdaQueryWrapper<Item> queryWrapper = Wrappers.lambdaQuery();
        // 根据更新日期降序排列
        queryWrapper.orderByDesc(Item::getCreated);
        if (!search.isEmpty())
            queryWrapper.like(Item::getSellPoint, search);
        return itemMapper.selectPage(page, queryWrapper);
    }

    //进行post获取商品详情数据列表
    @Override
    public Page<Item> findPages(Integer pageNum, Integer pageSize, String title) {
        Page<Item> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(title)) {
            queryWrapper.like(Item::getTitle, title);
        }
        queryWrapper.orderByDesc(Item::getCreated);
        return itemMapper.selectPage(page, queryWrapper);
    }


    @Override
    public Item findById(Integer id) {
        //找到ID相同的商品
        return itemMapper.selectOne(Wrappers.<Item>lambdaQuery().eq(Item::getId, id));
    }

    @Override
    public List<Item> findByCid(Integer cid) {
        LambdaQueryWrapper<Item> wrapper = Wrappers.<Item>lambdaQuery().eq(Item::getCid, cid);
        return itemMapper.selectList(wrapper);
    }

    //下载商品数据导入模板
    @Override
    public void downloadItemTemplate(HttpServletResponse response){
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("用户导入模板");
            Row headerRow = sheet.createRow(0);

            String[] headers = {"商品标题", "价格 ", "库存数量", "商品状态（1：正常，2：下架，3：删除）", "卖点", "商品图片url",};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            String fileName = URLEncoder.encode("user_template.xlsx", "UTF-8");
//            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            String fileName = URLEncoder.encode("商品导入模板.xlsx", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"; filename*=UTF-8''" + fileName);
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出模板失败", e);
        }
    }

    //导入商品数据
    @Override
    public void importItemExcel(MultipartFile file, boolean isCover) throws Exception {
        try (InputStream is = file.getInputStream();
             Workbook workbook = WorkbookFactory.create(is)) {

            Sheet sheet = workbook.getSheetAt(0);
            List<Item> itemList = new ArrayList<>();

            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                Item item = new Item();
                item.setTitle(getCellString(row.getCell(0)));
                item.setPrice(toBigDecimal(row.getCell(1)));
                item.setStock(getCellInt(row.getCell(2)));
                item.setStatus(getCellByte(row.getCell(3)));
                item.setSellPoint(getCellString(row.getCell(4)));
                item.setImage(getCellString(row.getCell(5)));
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                item.setCreated(LocalDateTime.now().format(formatter));
//                item.setUpdated(LocalDateTime.now().format(formatter));
                Date now = new Date();
                if (item.getCid() == null) {
                    item.setCid(1L);
                }
                item.setCreated(now);
//                item.setUpdated(now);
                itemList.add(item);
            }

            if (isCover) {
                List<String> title = itemList.stream()
                        .map(Item::getTitle)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());

                if (!title.isEmpty()) {
                    remove(new QueryWrapper<Item>().in("title", title));
                }
            }
            saveBatch(itemList);
        }
    }

    //公用方法
    @Override
    public void saveBatchItem(List<Item> items) {
        for (Item item : items) {
            itemMapper.insert(item);
        }
    }
    private String getCellString(Cell cell) {
        if (cell == null) return null;
        cell.setCellType(CellType.STRING);
        return cell.getStringCellValue().trim();
    }
    private Byte getCellByte(Cell cell) {
        if (cell == null) return null;
        try {
            if (cell.getCellType() == CellType.NUMERIC) {
                return (byte) cell.getNumericCellValue();
            } else {
                return Byte.parseByte(cell.getStringCellValue().trim());
            }
        } catch (Exception e) {
            return null;
        }
    }
    private BigDecimal toBigDecimal(Cell cell) {
        if (cell == null) return BigDecimal.ZERO;
        try {
            if (cell.getCellType() == CellType.NUMERIC) {
                return BigDecimal.valueOf(cell.getNumericCellValue());
            } else {
                return new BigDecimal(cell.getStringCellValue().trim());
            }
        } catch (Exception e) {
            return BigDecimal.ZERO; // 或根据需求抛异常
        }
    }

    private Integer getCellInt(Cell cell) {
        if (cell == null) return null;
        if (cell.getCellType() == CellType.NUMERIC) {
            return (int) cell.getNumericCellValue();
        } else {
            try {
                return Integer.parseInt(cell.getStringCellValue());
            } catch (Exception e) {
                return null;
            }
        }
    }

     //导出商品数据excel
    @Override
    public void exportItemData(HttpServletResponse response) {
        List<Item> itemList = itemMapper.selectList(null); // 查询所有用户

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("用户数据");

            // 表头
            String[] headers = {"商品ID", "商品昵称", "卖点", "商品图片连接", "价格", "库存","商品状态（1：正常，2：下架，3：删除）", "创建时间", "更新时间",};
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                headerRow.createCell(i).setCellValue(headers[i]);
                sheet.autoSizeColumn(i);
            }

            // 写入用户数据
            for (int i = 0; i < itemList.size(); i++) {
                Item item = itemList.get(i);
                Row row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(item.getId());
                row.createCell(1).setCellValue(item.getTitle());
                row.createCell(2).setCellValue(item.getSellPoint());
//                row.createCell(3).setCellValue(item.getPrice());
                row.createCell(3).setCellValue(item.getPrice().doubleValue());
                row.createCell(4).setCellValue(item.getImage());
                row.createCell(5).setCellValue(item.getStatus());
                row.createCell(5).setCellValue(item.getStock());
                row.createCell(7).setCellValue(item.getCreated());
                row.createCell(8).setCellValue(item.getUpdated());
            }

            // 设置导出文件属性
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = URLEncoder.encode("商品数据.xlsx", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出失败：" + e.getMessage(), e);
        }
    }

}
